<?/* 仕事表出力ユーティリティ */

$db = new PDO('mysql:host=localhost;dbname=work');
$db->query('set names utf8');

function print_jobs($db, $jobs, $memberID = -1){
  echo '<form action="message.php" method="POST">';
  foreach($jobs as $job){
    $kind = $job->buyer && $job->seller ? 'done' : ($job->buyer?'buy':'sell');
    $cap = $kind == 'done' ? '済み' : ($kind=='buy'?'雇う':'働く');
    $edit = $memberID === $job->buyer || $memberID === $job->seller ?
      T('div', array('class'=>'owner'),
        T('a', array('class'=>'edit',
                     'href'=>"edit_job.php?jobid=$job->jobID"),
          '編集').
        T('a', array('class'=>'delete',
                     'href'=>"delete_job.php?jobid=$job->jobID"),
          '削除')) : '';
    echo <<<JobTable
 <table id="job-$job->jobID" class="job $kind">
  <caption>$cap $edit</caption>
  <tr><th>内容</th><td>$job->worktext</td></tr>
  <tr><th>地域</th><td>$job->area</td></tr>
  <tr><th>賃金</th><td>$job->fee</td></tr>
  <tr><th>時間</th><td>$job->zikantai</td></tr>
  <tr><th>資格</th><td>$job->license</td></tr>
JobTable;
    $st = $db->prepare('select subtag from categories where jobID = ?');
    if($st->execute(array($job->jobID)) &&
       ($tags = $st->fetchAll(PDO::FETCH_COLUMN))){
      echo '<tr class="tag"><th>タグ</th><td>';
      foreach($tags as $tag) echo " $tag ";
      echo "</td></tr>\n";
    }
    echo '</table>';
    messages($db, $job->jobID);
    if($memberID > 0){
      $rid = "radio$job->jobID";
      echo <<<RADIO
 <label for="$rid" class="jobselect">
   <input type="radio" id="$rid" name="jid" value="$job->jobID" />
   ここへ投稿
 </label>
RADIO;
    }
  }
  if($memberID > 0) echo <<<FORM
 <pre id="msgform">
タイトル：<input type="text" name="sbj" />
　　内容：<textarea name="bdy" cols="20" rows="6"></textarea>
　　　　　<input type="submit" />
 </pre>
FORM;
  echo '</form>';
}

function messages($db, $jobID){
  echo "<ul class=\"messages\">\n";
  $st = $db->prepare('select date, subject, body, nickname, sender'.
                     ' from messages, members'.
                     ' where jobID = :jid and sender = memberID'.
                     ' order by date');
  $st->bindParam(':jid', $jobID, PDO::PARAM_INT);
  if($st->execute()) foreach($st->fetchAll(PDO::FETCH_OBJ) as $msg){
    echo T('li', array('class'=>'message'),
           T('span', array('class'=>'subject'), $msg->subject).
           T('a', array('class'=>'nick', 'href'=>"mypage.php?m=$msg->sender"),
             $msg->nickname).
           T('span', array('class'=>'date'), $msg->date).
           T('div', array('class'=>'body'), $msg->body));
  }
  echo "</ul>\n";
}

function T($name, $attr, $content){
  $t = "<$name";
  foreach($attr as $k => $v) $t .= ' '. $k .'="'. $v .'"';
  return "$t>$content</$name>\n";
}
